<?php
/**
 * ACL plugin for front controller
 * 
 * @author vsemaphore
 * @version $Id: AccessControlPlugin.php 237 2009-07-03 10:09:59Z nazin $
 *
 */
class Bib_AccessControlPlugin extends Zend_Controller_Plugin_ErrorHandler {
	
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		$auth = Zend_Auth::getInstance();
		$auth->setStorage(new Zend_Auth_Storage_Session(Zend_Registry::get('auth')->sessionNamespace));
		$ident = $auth->getIdentity();
		
		if ( $ident instanceof User) {
			$role = $ident->rola;
		} else {
			$role = Zend_Registry::get('config')->auth->defaultRole;
		}
		
		//var_dump($ident, $role);die;
		
		$acl = new Bib_Acl();
		Zend_Registry::set('Acl', $acl);
	
		$resource = $acl->has($request->getControllerName()) ? $request->getControllerName() : null;
//		var_dump($role, $resource, $request->getActionName(), $acl->isAllowed($role, $resource, $request->getActionName())); die;
		if(Zend_Registry::get('acl')->checkResourceExistense && $resource == null)
			$exception = new Zend_Acl_Exception('Resource '. $request->getControllerName(). ' not found.');
		else if(!$acl->isAllowed($role, $resource, $request->getActionName())) {			
			$exception = new Zend_Acl_Exception('User not allowed!');
		}

		//var_dump($exception); die;
		
		if(isset($exception)) {
        	$error = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); 
            $error->request = clone $request;  
            $error->exception = $exception; 
            $error->type = parent::EXCEPTION_OTHER;  
        	$request->setParam('error_handler', $error)
                    ->setModuleName( $this->getErrorHandlerModule())
                    ->setControllerName($this->getErrorHandlerController())
                    ->setActionName($this->getErrorHandlerAction());
		}
		
	}
	
}